package com.xinjian.jianba.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.GsonBuilder;
import com.xinjian.jianba.dto.PerEditerDto;
import com.xinjian.jianba.exception.ResponseCode;
import com.xinjian.jianba.service.QiNiuService;
import com.xinjian.jianba.service.ValidatorService;
import com.xinjian.jianba.utils.LogBuilder;
import com.xinjian.jianba.utils.ModuleEnum;
import com.xinjian.jianba.utils.QiNiuUtil;
import com.xinjian.jianba.utils.RongYunUtil;

@RestController
@RequestMapping(value="/api/v3/jianba/qiniuyun")
public class QiniuYunController extends AbstractController{
	private static final Logger LOGGER = LoggerFactory.getLogger(QiniuYunController.class);

	@Autowired
	private QiNiuService qiNiuService;
	@Autowired
	private ValidatorService validatorService;
	@Value("${jianba.qiniu.protocol}")
	private String protocol;
	@PostMapping("/token")
	public String getToken(@RequestBody Map<String, String> map){
		LOGGER.info(LogBuilder.build(ModuleEnum.QiniuYun, "获取七牛云token"));
		String action=map.get("action");
		if(action==null||action.equals("")){
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "action不能为空");
		}
		//覆盖上传
		if(action.equals("logo")){
			String fileName=map.get("fileName");
			String userDefined=map.get("userDefined");
			if(fileName==null||fileName.equals("")){
				return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "fileName不能为空");
			}
			String token=QiNiuUtil.getToken(fileName, userDefined==null?"":userDefined,true);//覆盖上传
			return QiNiuUtil.extractObjectToJsonStr(token);
		}else if(action.equals("mons")||action.equals("personEditer")){
			String fileName=map.get("fileName");
			String userDefined=map.get("userDefined");
			if(fileName==null||fileName.equals("")){
				return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "fileName不能为空");
			}
			String token=QiNiuUtil.getToken(fileName, userDefined==null?"":userDefined,false);//增量上传
			return QiNiuUtil.extractObjectToJsonStr(token);
		}else{
			return this.responseClientJsonData(ResponseCode.BAD_REQUEST, "action不合法");
		}
	}
	@PostMapping("/callBack")
	public String callBack(HttpServletRequest request) throws UnsupportedEncodingException{
		LOGGER.info(LogBuilder.build(ModuleEnum.QiniuYun, "七牛云接口回调"));
		StringBuffer json;
		try {
			json = QiNiuUtil.extractedRequestToStringBuffer(request);
		} catch (IOException e) {
			return this.responseClientJsonData(ResponseCode.ERROR, e.getMessage());
		}
		String result=  json.toString().replaceAll("&", ",");
		String[] str=result.split(",");
		String action="";
		String key="";
		String userId="";
		for(String strTemp:str){
			if(strTemp!=null){
			int a=strTemp.indexOf("action=");
			if(a>=0){
				action=strTemp.substring(strTemp.indexOf("=")+1);
			}
			int b=strTemp.indexOf("key=");
			if(b>=0){
				key=strTemp.substring(strTemp.indexOf("=")+1);
			}
			}
			int c=strTemp.indexOf("userId=");
			if(c>=0){
				userId=strTemp.substring(strTemp.indexOf("=")+1);
			}
		}
		if(key.startsWith("\"")){
			key=key.substring(1).trim();
		}
		if(key.endsWith("\"")){
			key=key.substring(0, key.length()-1).trim();
		}
		if(userId.startsWith("\"")){
			userId=userId.substring(1).trim();
		}
		if(userId.endsWith("\"")){
			userId=userId.substring(0, userId.length()-1).trim();
		}
		
		String address=protocol+"://"+QiNiuUtil.domainOfBucket+"/"+key;
//		String dbAdress=URLDecoder.decode(address, "utf-8");
		result=result.replaceAll("=", ":");
		Map<String,String> map=new HashMap<String,String>();
		map.put("address", address);
		String Jsonstr=QiNiuUtil.extractObjectToJsonStr(map);
		if("\"personEditer\"".equals(action)){
			String reStr=qiNiuService.savePersonalDataeEitor("{"+result+"}",address);
			if("SUCCESS".equals(reStr)){
				LOGGER.info("-----personEditer--------" + Jsonstr);
				return Jsonstr;
			}else{
				LOGGER.info("-----personEditer--------" + reStr);
				return this.responseClientJsonData(ResponseCode.ERROR, reStr);
			}
		}
		if("\"logo\"".equals(action)){
			if("null".equals(userId)||"".equals(userId)||userId==null){
				LOGGER.info("-----logo--------" + Jsonstr);
				return this.responseClientJsonData(ResponseCode.ERROR, "userId不能为空,上传失败");
			}
			Map<String,Object> mapLogo=qiNiuService.upLogo(userId, address);
//			String rongYunMesage="";
//			try {
//				qiNiuService.updateRongYunToken(userId, address);
//			} catch (Exception e) {
//				return this.responseClientJsonData(ResponseCode.ERROR, "融云头像更新失败");
//			}
			int re=(int) mapLogo.get("re");
			map.put("address", (String)mapLogo.get("address"));
			Jsonstr=QiNiuUtil.extractObjectToJsonStr(map);
			if(re==1){
				LOGGER.info("-----logo--------" +Jsonstr);
				return Jsonstr;
			}else{
				LOGGER.info("-----logo--------" + Jsonstr);
				return this.responseClientJsonData(ResponseCode.ERROR, "上传头像失败");
			}
		}
		if("\"mons\"".equals(action)){
			LOGGER.info("-----mons--------" +Jsonstr);
			return Jsonstr;
		}
		LOGGER.info("-----resultStr--------" + "请传入正确的action的值");
		 return this.responseClientJsonData(ResponseCode.ERROR, "请传入正确的action的值");
	}
	@PostMapping("delete/personEditer")
	public String deletePersonEditer(@RequestBody PerEditerDto PerEditerDto){
		try {
			validatorService.valid(PerEditerDto);
		} catch (Exception e) {
			return responseClientJsonData(ResponseCode.BAD_REQUEST, e.getMessage());
		}
		String result=qiNiuService.deletePerEditor(PerEditerDto);
		if("SUCCESS".equals(result)){
			return responseClientJsonData(ResponseCode.SUCCESS, ResponseCode.SUCCESS_MSG);
		}else{
			return responseClientJsonData(ResponseCode.ERROR, "目标资源不存在");
		}
		
	}
	@PostMapping("Jian/image")
	public String jianImage(@RequestBody Map<String,String> map){
		String image64=map.get("image64");
		if(image64==null||image64.equals("")){
			return responseClientJsonData(ResponseCode.BAD_REQUEST, "image64不能为空");
		}
		QiNiuUtil.sanjian(image64);
		return this.responseClientJsonData(ResponseCode.SUCCESS, "合法图片");
	}
}
